const Router = require("koa-router");
const router = new Router();
const jsonwebtoken = require("jsonwebtoken");
const jwt = require("koa-jwt");
const {
  login,
  createUser,
  listUsers,
  resolveIp,
} = require("../controllers/user");
// 用户路由前缀
router.prefix("/users");

// 鉴权中间件
const auth = async (ctx, next) => {
  console.log("代码执行测试");
  // 注意是小写
  const { authorization = "" } = ctx.request.header;
  const token = authorization.replace("Bearer ", "");

  try {
    const user = jsonwebtoken.verify(token, process.env.tokenSecret);
    console.log(user, "user");
    // 将用户的信息挂载到命名空间上面去
    ctx.state.user = user;
    await next();
  } catch (error) {
    ctx.throw(401, "没有权限");
  }
};
const auth1 = jwt({ secret: process.env.tokenSecret });

// 用户登录
router.post("/login", login);
// 增加用户
router.get("/", auth1, listUsers);
// 解析用户IP地址为地理位置
router.get("/ip", resolveIp);
// 创建新用户，需要鉴权处理
router.post("/", createUser);

module.exports = router;
